package com.augrain.microframework.web.sensitive;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.util.Objects;

public class SensitiveJsonSerialize extends JsonSerializer<String> implements ContextualSerializer {

    private SensitiveStrategy strategy;

    // 在序列化时进行数据脱敏
    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(strategy.desensitizeSerializer().apply(value));
    }

    // 获取注解上的属性
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property) throws JsonMappingException {
        Sensitive annotation = property.getAnnotation(Sensitive.class);
        if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass())) {
            // 主要代码在这里，获取脱敏的规则
            this.strategy = annotation.strategy();
            return this;
        }
        return provider.findValueSerializer(property.getType(), property);

    }
}